package com.icw.configuration.database;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.icw.decoupling.defi.proxy.GenericSrvProxy;

@Component
public class DropOne2OneIdConstraint implements InitializingBean {

	private static String FK_QUERY_SQL = ""// e
			+ "select "// e
			+ "table_name, "// e
			+ "constraint_name "// e
			+ "from "// e
			+ "information_schema.`KEY_COLUMN_USAGE` "// e
			+ "where "// e
			+ "constraint_name like 'fk%' "// e
			+ "and CONSTRAINT_SCHEMA = ? "// e
			+ "and column_name = 'id'";// e

	@Autowired
	EntityManager em;

	@Autowired
	GenericSrvProxy serv;

	@Override
	public void afterPropertiesSet() throws Exception {
		serv.exec(() -> {
			Query query = em.createNativeQuery(FK_QUERY_SQL).setParameter(1, getSchemaName());
			List<?> list = query.getResultList();
			for (Object temp : list) {
				Object[] tb_fk = (Object[]) temp;
				em.createNativeQuery(String.format("ALTER TABLE %s DROP FOREIGN KEY %s", tb_fk)).executeUpdate();
			}
			return null;
		});
	}

	@Value("${spring.datasource.url}")
	private String jdbcUrl;

	private String getSchemaName() throws Exception {
		return __getSchemaName(jdbcUrl);
	}

	private static String __getSchemaName(String jdbcUrl) throws Exception {
		Matcher m = Pattern.compile("/[^/\\?]+\\?").matcher(jdbcUrl);
		if (m.find()) {
			return m.group().substring(1, m.group().length() - 1);
		} else {
			throw new Exception("Parsing Shcema error.");
		}
	}
}
